<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="课程分类" prop="categoryId">
              <el-select clearable v-model="queryParams.categoryId"  @change="typeHandleCourse($event)" placeholder="请选择课程分类" class="w-full">
                <el-option
                  v-for="item in courseType"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="关联课程" >
            <el-select v-model="queryParams.courseId" clearable placeholder="请选择关联课程" class="w-full" @keyup.enter="handleQuery">
                      <el-option
                        v-for="item in courseOptions"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
            <el-form-item label="支付金额" prop="amount">
              <el-input v-model="queryParams.amount" placeholder="请输入支付金额" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="用户">
            <el-select v-model="queryParams.userId" clearable placeholder="请选择用户" filterable class="w-full" @keyup.enter="handleQuery">
                  <el-option
                    v-for="item in userOptions"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                  />
                </el-select>
              </el-form-item>
            <el-form-item label="支付时间" prop="payTime">
              <el-date-picker clearable
                v-model="queryParams.payTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择支付时间"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['bykt:order:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['bykt:order:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['bykt:order:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <!-- <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['bykt:order:export']">导出模版</el-button> -->
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column label="用户" align="center" prop="nickName" />
        <el-table-column label="课程" align="center" prop="title" />
        <el-table-column label="支付金额" align="center" prop="amount" />
        <el-table-column label="状态" align="center" prop="status" >
          <template #default="scope">
            <span>{{ scope.row.status == 0 ? '未支付' : scope.row.status == 1 ?'已支付' :"已取消"}}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center" prop="payType" >
          <template #default="scope">
            <span>{{ scope.row.payType === 1 ? '微信支付' : scope.row.payType === 2 ?'支付宝支付' :"余额支付"}}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付时间" align="center" prop="payTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bykt:order:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bykt:order:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改课程订单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="orderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="userId">
          <el-select clearable placeholder="请选择用户" v-model="form.userId" filterable class="w-full" @change="handleUserChange">
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.nickName || item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="课程" prop="courseId" >
          <template v-if="!form.id">
            <MenuPermission
              ref="menuPermission"
              v-model="form.courseId"
              :menuOptions="deptOptions"
              @change="handleCourseChange"
            ></MenuPermission>
          </template>
          <template v-else>
            <el-radio-group v-model="form.courseId" class="w-full">
              <el-radio
                v-for="item in courseOptions"
                :key="item.id"
                :label="item.id"
              >
                {{ item.title }}
              </el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <el-form-item label="支付金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入支付金额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder,getDeptOptions } from '@/api/bykt/order/index';
import { useUserStore } from '@/store/modules/user';
import MenuPermission from '@/components/MenuPermission/index.vue'

const { proxy } = getCurrentInstance();
import { getCourseList, getCategoryTypeList } from '@/api/bykt/course/index';
import { listUser } from '@/api/bykt/student/index';
const userStore = useUserStore();
const orderList = ref([]);
const buttonLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref();
const orderFormRef = ref();
const deptOptions = ref([]);
const courseType = ref([]);
const typeIds = ref([]);
const dialog = reactive({
  visible: false,
  title: ''
});

const initFormData = {
  id: undefined,
  orderNo: undefined,
  userId: undefined,
  courseId: [], // 修改为数组类型
  amount: undefined,
  status: undefined,
  payType: undefined,
  payTime: undefined,
  remark: undefined
};

const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    userId: undefined,
    courseId: undefined,
    amount: undefined,
    status: undefined,
    payType: undefined,
    payTime: undefined,
    params: {}
  },
  rules: {
    id: [
      { required: true, message: "订单ID不能为空", trigger: "blur" }
    ],
    orderNo: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户不能为空", trigger: "blur" }
    ],
    courseId: [
      {
        required: true,
        message: "课程不能为空",
        trigger: "blur",
        validator: (rule, value, callback) => {
          if (!value || (Array.isArray(value) && value.length === 0)) {
            callback(new Error("请选择课程"));
          } else {
            callback();
          }
        }
      }
    ],
    amount: [
      { required: true, message: "支付金额不能为空", trigger: "blur" }
    ],
  }
});
const courseTreeRef = ref(null);

const courseOptions = ref([]);
const userOptions = ref([]);
const isAllCoursesSelected = ref(false);

const handleUserChange = () => {
  isAllCoursesSelected.value = false;
};
const handleCourseTreeCheck = (checkedKeys) => {
  // 获取当前选中的节点
  const checkedNodes = courseTreeRef.value.getCheckedNodes();
  // 更新表单的 courseId
  form.value.courseId = checkedNodes.map(node => node.id);
};


const fetchCourseList = async () => {
  try {
    const res = await getCourseList({});
    courseOptions.value = res.rows || [];
  } catch (error) {
    console.error("获取课程列表失败:", error);
  }
};

const fetchUserList = async () => {
  try {
    const res = await listUser({});
    userOptions.value = res.rows || [];
  } catch (error) {
    console.error("获取用户列表失败:", error);
  }
};

const { queryParams, form, rules } = toRefs(data);

const getList = () => {
  loading.value = true;
  listOrder(queryParams.value).then(res => {
    orderList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  })
}

const cancel = () => {
  reset();
  dialog.visible = false;
}

const reset = () => {
  form.value = {...initFormData};
  orderFormRef.value?.resetFields();
  if(courseTreeRef.value) {
    courseTreeRef.value.setCheckedKeys([]);
  }
  // 重置树形控件的选中状态
}

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.courseId = undefined;
  handleQuery();
  fetchCourseList();
}

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const handleAdd = () => {
  reset();  // 调用重置方法清除之前的选择
  dialog.visible = true;
  dialog.title = "添加课程订单";
  console.log(form.value)

  // // 确保树形控件已渲染后重置选中状态
}

const handleUpdate = async (row) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改课程订单";
}

/** 处理课程选择变化 */
const handleCourseChange = (value) => {
  form.value.courseId = value;
};

// 修改提交方法
const submitForm = () => {
  orderFormRef.value?.validate(async (valid) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateOrder(form.value, form.value.userId);
        } else {
          const { courseId, ...formData } = form.value;
          const filteredCourseId = courseId.filter(id => !typeIds.value.includes(id));
          formData.courseIds = filteredCourseId.join(',');
          await addOrder(formData, form.value.userId);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        form.value = { ...initFormData };
        // 清空 MenuPermission 组件的选中状态
        const menuPermissionRef = proxy?.$refs.menuPermission;
        if (menuPermissionRef) {
          menuPermissionRef.reset();
        }
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

const handleDelete = async (row) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除课程订单编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delOrder(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

const typeHandleCourse = async (categoryId) => {
  try {
    const res = await getCourseList({categoryId});
    queryParams.value.courseId = undefined;
    courseOptions.value = res.rows || [];
  } catch (error) {
    console.error("获取课程列表失败:", error);
  }
}

const fetchCourseTypeList = async () => {
  try {
    const res = await getCategoryTypeList({});
    courseType.value = res.rows || [];
  } catch (error) {
    console.error("获取课程分类列表失败:", error);
  }
}
const getDeptOptionsData = async () => {
  try {
    const res = await getDeptOptions();
    res.data?.forEach(item => {
      // item.disabled = true
      typeIds.value.push(item.id);
    }) || [];
    console.log(typeIds.value);
    deptOptions.value = res.data || [];
    console.log(deptOptions.value); // 打印获取到的部门列表数据
  } catch (error) {
    console.error("获取部门列表失败:", error);
  }
};
onMounted(() => {
  getList();
  fetchCourseTypeList();
  fetchCourseList();
  fetchUserList();
  getDeptOptionsData()
});
</script>
